//
//  DerbyNSOdeLog.m
//  DerbyOSSampler
//
//  Created by glenn andreas on 1/7/14.
//  Copyright (c) 2014 glenn andreas. All rights reserved.
//

#import "DerbyNSOdeLog.h"
#import <stdarg.h>
@interface DerbyNSOdeLog()
@property (strong) NSString *name;
@end

@implementation DerbyNSOdeLog
+ (DerbyNSOdeLog *) logNamed: (NSString *) name
{
    static NSMutableDictionary *logs = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        logs = [NSMutableDictionary new];
    });
    if ([logs objectForKey:name]) {
        return [logs objectForKey:name];
    }
    DerbyNSOdeLog *retval = [self new];
    retval.name = name;
#if TARGET_OS_IPHONE
#else
    // use bindings to detect when the key path changes, and bind such that we always are the correct value
    NSUserDefaultsController *udc = [NSUserDefaultsController sharedUserDefaultsController];
    NSString *keyPath =[@"defaults.DerbyNSOdeLog." stringByAppendingString:name];
    retval.log = [[udc valueForKeyPath:keyPath] intValue];
    [udc addObserver:retval forKeyPath:keyPath options:0 context:NULL];
#endif
    [logs setObject:retval forKey:name];
    return retval;
}
- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    self.log = [[object valueForKeyPath:keyPath] intValue];
}
- (void) log: (DerbyNSOdeLogLevel) level message:(NSString *)format, ...
{
    if (level == DerbyNSOdeLogError || level <= self.log) {
        va_list varg;
        va_start(varg, format);
        NSString *msg = [[NSString alloc] initWithFormat:format arguments:varg];
        NSLog(@"%@:%@",self.name,msg);
        va_end(varg);
    }
}
@end
